"""
启动脚本
用于启动AI合同审核系统
"""

import os
import sys
import subprocess
from pathlib import Path

def check_dependencies():
    """检查依赖包是否安装"""
    required_packages = [
        'streamlit',
        'openai',
        'PyPDF2',
        'python-docx',
        'pdfplumber'
    ]
    
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package.replace('-', '_'))
        except ImportError:
            missing_packages.append(package)
    
    if missing_packages:
        print("❌ 缺少以下依赖包:")
        for package in missing_packages:
            print(f"   - {package}")
        print("\n请运行以下命令安装依赖:")
        print("pip install -r requirements.txt")
        return False
    
    print("✅ 所有依赖包已安装")
    return True

def setup_environment():
    """设置环境"""
    project_root = Path(__file__).parent
    
    # 创建必要的目录
    directories = ['uploads', 'reports', 'templates', 'static']
    for dir_name in directories:
        dir_path = project_root / dir_name
        dir_path.mkdir(exist_ok=True)
        print(f"✅ 目录已创建: {dir_name}")

def main():
    """主函数"""
    print("🚀 启动AI合同审核系统...")
    print("=" * 50)
    
    # 检查依赖
    if not check_dependencies():
        sys.exit(1)
    
    # 设置环境
    setup_environment()
    
    # 启动Streamlit应用
    print("\n🌐 启动Web界面...")
    print("请在浏览器中访问: http://localhost:8501")
    print("按 Ctrl+C 停止服务")
    print("=" * 50)
    
    try:
        subprocess.run([
            sys.executable, "-m", "streamlit", "run", "main.py",
            "--server.port", "8501",
            "--server.address", "localhost"
        ])
    except KeyboardInterrupt:
        print("\n👋 系统已停止")
    except Exception as e:
        print(f"❌ 启动失败: {e}")

if __name__ == "__main__":
    main()
